package com.siyoumi.app.sys.service.file;

import com.siyoumi.app.external_api.aliyun.ApiAliYunOss;
import com.siyoumi.app.external_api.aliyun.entity.EnvAlipayOss;
import com.siyoumi.app.sys.service.CommonApiServcie;
import com.siyoumi.app.sys.service.FileHandle;
import com.siyoumi.app.sys.service.file.entity.FileUploadData;
import com.siyoumi.component.XApp;
import com.siyoumi.config.SysConfig;
import com.siyoumi.exception.EnumSys;
import com.siyoumi.util.XDate;
import com.siyoumi.util.XReturn;
import com.siyoumi.util.XStr;
import com.siyoumi.validator.XValidator;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

//阿里云
public class FileHandleAliyun
        extends FileHandle {
    /**
     * 获取直接跳转链接
     *
     * @param fileVal
     */
    static public String getRedirectFileUrl(String fileVal) {
        String appRoot = SysConfig.getIns().getAppRoot();

        return XStr.format("{0}aliyun/{1}.file", appRoot, fileVal);
    }

    @Override
    protected XReturn saveFile(FileUploadData data) {
        if (XStr.isNullOrEmpty(data.getSaveFileDir())) {
            return EnumSys.MISS_VAL.getR("保存文件目录不能为空");
        }
        ApiAliYunOss api = ApiAliYunOss.of(EnvAlipayOss.getBean());

        File file = CommonApiServcie.toFile(data.getMultFile());
        String ossFilePath = XStr.format("{0}/{1}.{2}"
                , data.getSaveFileDir()
                , XApp.getStrID()
                , getFileExt(data.getMultFile().getOriginalFilename())
        );

        XReturn r;
        try {
            r = api.uploadFile(ossFilePath, file);
            XValidator.err(r);
        } catch (Exception ex) {
            throw ex;
        } finally {
            file.delete();
        }
        
        r.setData("file_val", ossFilePath);
        r.setData("file_url", getRedirectFileUrl(ossFilePath));

        return r;
    }

    @Override
    public String getFileUrl(String fileVal) {
        ApiAliYunOss api = ApiAliYunOss.of(EnvAlipayOss.getBean());
        XReturn r = api.generatePresignedUrl(fileVal);
        if (r.err()) {
            XValidator.err(r);
        }

        return r.getData("url");
    }
}
